# coding:utf-8
# 用于更新shadowsock的链接密码,并自动重启SS
# 使用方法：把本文件放在ShadowSocks的根目录下，双击即可更新。如果路径及其他文件名有修改请更新后在使用
# author=Crowhyc


import urllib.request, re, json, os, sys


def getHtml(url):
    pageData = urllib.request.urlopen(url).read()
    return pageData


def colonFilter(data):
    return re.split(":", data)[1]


def getPassword(data):
    data = data.decode("utf-8")
    nFilter = re.compile("\\n|\\r|\\s")
    data = nFilter.sub('', data)
    # regex =r'<h4>[A-Z]密码:(\w+|\s+)</h4>'
    regex = r'<divclass="col-lg-4text-center"><h4>[A-C].+?</div>'
    pwdre = re.compile(regex)
    pwdlist = re.findall(pwdre, data)
    pwdrere = re.compile('<divclass="col-lg-4text-center">|</div>|<h4>')
    list = []
    for ret in pwdlist:
        list.append(pwdrere.sub('', ret))
    listDict = []
    for rett in list:
        filterData = re.split(r'</h4>', rett)
        if (len(colonFilter(filterData[2])) > 0):
            listDict.append({'ip': colonFilter(filterData[0]), 'port': colonFilter(filterData[1]),
                             'password': colonFilter(filterData[2]), 'method': colonFilter(filterData[3])})
    return listDict


def inputPassword(path, data):
    jsonFile = open(path)
    jsonData = json.loads(jsonFile.read())
    for ret in data:
        flag = False
        for jd in jsonData['configs']:
            if (ret['ip'].upper() == jd['server']):
                flag = True
                print(jd['server'] + '密码更新成功')
                jd['password'] = ret['password']
        if (not flag):
            newSever = {'server': ret['ip'].upper(), 'server_port': int(ret['port']), 'password': ret['password'],
                        'method': ret['method'], 'remark': ''}
            jsonData['configs'].append(newSever)
            print(ret['ip'].upper() + "被添加")
            flag = True
    json.dump(jsonData, open(path, 'w'))
    jsonFile.close()


def rebootExe(filename):
    closeCommand = 'taskkill /F /IM ' + filename;
    os.system(closeCommand)
    os.popen(os.getcwd() + "/" + filename)
    sys.exit(0)


if (__name__ == "__main__"):
    data = getPassword(getHtml("http://www.ishadowsocks.net"))
    jsonData = inputPassword(os.getcwd() + '/gui-config.json', data)
    rebootExe('ShadowSocks.exe')
